#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

void CreateDaemon()
{
    pid_t pid;

    pid=fork();
    if(pid<0)
    {
        perror("fork err\n");
        return;
    }
    else if(pid>0)
    {
        exit(0);
    }
    else
    {
        if(setsid()==-1)
        {
            printf("setsid err\n");
            exit(1);
        }
        pid=fork();
        if(pid<0)
        {
            perror("fork err");
            return;
        }
        else if(pid>0)
        {
            exit(0);
        }
        else
        {
            chdir("/");
            for (int i = 0; i < 3; i++)
            {
                close(i);
            }
            umask(0);
            return ;
        }
    }
}

int main(int argc,char const *argv[])
{
    int fd_fifo=-1;
    int fd_dest=-1;
    char buf[32]={'\0'};
    int count=0;

    if(mkfifo("./fifo",0666)==-1)
    {
        if(errno==EEXIST)
        {
            printf("fifo exist\n");
        }
        else
        {
            perror("mkfifo err\n");
            return -1;
        }
    }

    fd_fifo=open("./fifo",O_RDONLY);
    if(fd_fifo<0)
    {
        perror("fifo open err\n");
        return -1;
    }
    fd_dest=open("dest.c",O_WRONLY|O_APPEND|O_CREAT,0666);
    if(fd_dest<0)
    {
        close(fd_fifo);
        perror("dest open err\n");
        return -1;
    }
    
    while (1)
    {
        while((count=read(fd_fifo,buf,32))!=0)
        {
            write(fd_dest,buf,count);
        }        
    }
    
    close(fd_dest);
    close(fd_fifo);

    return 0;
}